﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using iCollect.Chart;
using iCollect.Constants;
using System.Collections;
using iCollect.util;
using iCollect.Events;
using iCollect.CustomComponent;

namespace iCollect.CollectDetail
{
    public partial class OnlineCollect1 : UserControl
    {
        private BaseDeviceMonitor dMonitor;

        private LineChartType chart1 = new LineChartType();

        private bool inAlertStatus = false;

        public OnlineCollect1()
        {
            InitializeComponent();
            
            //dMonitor.Dock = System.Windows.Forms.DockStyle.Fill;
            //panel2.Controls.Add(dMonitor);
            //dMonitor.RaiseCustomEvent += HandleCustomEvent;

            
            chart1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.tabPage10.Controls.Add(chart1);
        }

        public void loadDevice()
        {
            dMonitor = UIUtil.getInstance().loadMonitor(dMonitor, panel2, HandleCustomEvent);
            loadAlertValue();
        }

        private void loadAlertValue()
        {
            GlobalConstants.channelAlert = new Dictionary<String, ArrayList>();

            string id = GlobalConstants.currentDevice;
            DataTable dtft = channelftTableAdapter.GetDataBy3(id);
            DataTable dtpt = channelptTableAdapter.GetDataBy3(id);
            DataTable dtrt = channelrtTableAdapter.GetDataBy3(id);
            DataTable dtte = channelteTableAdapter.GetDataBy3(id);
            DataTable dtvt = channelvtTableAdapter.GetDataBy3(id);

            appendAlertValue(dtft);
            appendAlertValue(dtpt);
            appendAlertValue(dtrt);
            appendAlertValue(dtte);
            appendAlertValue(dtvt);

            inAlertStatus = false;
        }

        private void appendAlertValue(DataTable dt)
        {
            DataRowCollection dtRows= dt.Rows;
            int alert1, alert2, stop1, stop2;
            string channelID;
            foreach (DataRow row in dtRows)
            {
                alert1 = (int)row["alert1"];
                alert2 = (int)row["alert2"];
                stop1 = (int)row["stop1"];
                stop2 = (int)row["stop2"];
                channelID = row[0].ToString();
                //decimal.TryParse(row[2].ToString(), out d1);
                ArrayList al = new ArrayList();
                al.Add(alert1);
                al.Add(alert2);
                al.Add(stop1);
                al.Add(stop2);
                GlobalConstants.channelAlert[channelID] = al;
            }
            
        }

        private bool channelSelected = false;
        private bool isReal = false;

        private string currentChannel;
        // Define what actions to take when the event is raised.
        public void HandleCustomEvent(object sender, EventArgs e)
        {
            if (e is CustomEventArgs)
            {
                CustomEventArgs ce = (CustomEventArgs)e;
                if (ce.state.Equals(CustomEventArgs.EXCEPTION_STATUS))
                {
                    stopMonitor();
                }
                else if (ce.state.Equals(CustomEventArgs.ALERT_STATUS)
                    || ce.state.Equals(CustomEventArgs.STOP_STATUS))
                {
                    this.inAlertStatus = true;
                }
            }
            else
            {
                HandleEvent(sender);
            }
        }

        private void HandleEvent(object sender)
        {
            channelSelected = true;
            channelInit = false;
            if (sender is TextBox)
            {
                TextBox tb = (TextBox)sender;
                //Modbus
                if (tb.Name.Substring(0, 2) == "tb")
                {
                    isReal = true;
                    currentChannel = tb.Name.Substring(2);
                    chart1.InitByChannel(currentChannel);
                }
                //NI
                else
                {
                    isReal = false;
                    chart1.InitPoints();
                }
            }
        }


        private void tabPage10_Click(object sender, EventArgs e)
        {

        }

        private void button6_Click(object sender, EventArgs e)
        {
            GlobalConstants.initCurrentData();
            addNormalDataIndex();
            addAlertDataIndex();
            startMonitor();
        }

        private void addNormalDataIndex()
        {
            foreach (string key in GlobalConstants.channelTypeMap.Keys)
            {
                checkChannelNormalDataIndex(key, GlobalConstants.channelTypeMap[key].ToString());
            }
        }

        private void checkChannelNormalDataIndex(string channelCode, string channelType)
        {
            DataTable td = normaldataTableAdapter.GetDataBy3(GlobalConstants.currentDevice,
                channelCode, DateTime.Today, false);
            if ( td.Rows.Count == 0)
            {
                normaldataTableAdapter.Insert(channelType, channelCode, DateTime.Today,
                    "数据库", GlobalConstants.currentDevice, false);
            }
            
        }

        private void addAlertDataIndex()
        {
            foreach (string key in GlobalConstants.channelTypeMap.Keys)
            {
                checkChannelAlertDataIndex(key, GlobalConstants.channelTypeMap[key].ToString());
            }
        }

        private void checkChannelAlertDataIndex(string channelCode, string channelType)
        {
            DataTable td = exceptiondataTableAdapter.GetDataBy3(GlobalConstants.currentDevice,
                channelCode, DateTime.Today);
            if (td.Rows.Count == 0)
            {
                exceptiondataTableAdapter.Insert(channelType, channelCode, DateTime.Today,
                    "数据库", GlobalConstants.currentDevice);
            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            stopMonitor();

            
        }

        private void stopMonitor()
        {
            button6.Enabled = true;
            button5.Enabled = false;
            button1.Enabled = false;
            timer1.Stop();
        }

        private void startMonitor()
        {
            button6.Enabled = false;
            button5.Enabled = true;
            button1.Enabled = true;
            timer1.Start();
        }

        private Random r1 = new Random();
        private int timerCount = 0;

        private bool channelInit = false;
        private void timer1_Tick(object sender, EventArgs e)
        {
            timerCount++;
            if (timerCount >= (GlobalConstants.configFreq * 60))
            {
                //FileUtil.getInstance().writeData();
                writeAutoData();
                timerCount = 0;
            }
            
            dMonitor.timer1_Tick();

            if (!channelSelected)
            {
                return;
            }
            
            if (isReal)
            {
                if (!channelInit)
                {
                    chart1.InitByChannel(currentChannel);
                    channelSelected = true;
                }
                else
                {
                    chart1.slideChannel(currentChannel);
                }
            }
            else
            {
                chart1.slidePoints(1);
            }
            
            //textBox1.Text = ((int)(r1.NextDouble() * 100.0)).ToString();
            //textBox2.Text = ((int)(r1.NextDouble() * 100.0)).ToString();
        }

        //private void writeAutoData()
        //{
        //    try
        //    {
        //        List<ArrayList> data;
        //        foreach (string key in GlobalConstants.currentData.Keys)
        //        {
        //            data = GlobalConstants.currentData[key];
        //            ArrayList timeValuePair = data[data.Count - 1];
        //            DateTime dt = (DateTime)timeValuePair[0];
        //            Double value = Double.Parse(timeValuePair[1].ToString());
        //            this.normaldataautoTableAdapter.InsertQuery(key, dt,
        //                value, 0, GlobalConstants.currentDevice);

        //            if (!GlobalConstants.channelAlert.ContainsKey(key))
        //            {
        //                continue;
        //            }
        //            ArrayList aList = (ArrayList)GlobalConstants.channelAlert[key];
        //            int alertValue1 = (int)aList[0];
        //            int alertValue2 = (int)aList[1];
        //            if (value >= alertValue2 || value <= alertValue1 ||
        //                (GlobalConstants.exceptionData[key].Count > 0 &&
        //                GlobalConstants.exceptionData[key].Count < GlobalConstants.exceptionCount))
        //            {
        //                exceptiondataautoTableAdapter.InsertQuery(key, dt,
        //                    value, 0, GlobalConstants.currentDevice);
        //                GlobalConstants.exceptionData[key].Add(timeValuePair);
        //                if (GlobalConstants.exceptionData[key].Count == 1)
        //                {
        //                    checkChannelExceptionDataIndex(key, GlobalConstants.channelTypeMap[key].ToString());
        //                }
        //            }
        //            //Need add exception interval later.
        //            if (GlobalConstants.exceptionData[key].Count >= GlobalConstants.exceptionCount)
        //            {
        //                GlobalConstants.exceptionData[key] = new List<ArrayList>();
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Console.Out.WriteLine(ex.Message);
        //    }
            
        //}

        private void writeAutoData()
        {
            try
            {
                List<ArrayList> data;
                if (inAlertStatus)
                {
                    foreach (string key in GlobalConstants.currentData.Keys)
                    {
                        data = GlobalConstants.currentData[key];
                        ArrayList timeValuePair = data[data.Count - 1];
                        DateTime dt = (DateTime)timeValuePair[0];
                        Double value = Double.Parse(timeValuePair[1].ToString());
                        exceptiondataautoTableAdapter.InsertQuery(key, dt,
                                value, 0, GlobalConstants.currentDevice);
                    }
                }
                else
                {
                    foreach (string key in GlobalConstants.currentData.Keys)
                    {
                        data = GlobalConstants.currentData[key];
                        ArrayList timeValuePair = data[data.Count - 1];
                        DateTime dt = (DateTime)timeValuePair[0];
                        Double value = Double.Parse(timeValuePair[1].ToString());
                        this.normaldataautoTableAdapter.InsertQuery(key, dt,
                            value, 0, GlobalConstants.currentDevice);
                    }
                }
                inAlertStatus = false;
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine(ex.Message);
            }

        }

        private void checkChannelExceptionDataIndex(string channelCode, string channelType)
        {
            DataTable td = exceptiondataTableAdapter.GetDataBy3(GlobalConstants.currentDevice,
                channelCode, DateTime.Today);
            if (td.Rows.Count == 0)
            {
                exceptiondataTableAdapter.Insert(channelType, channelCode, DateTime.Today,
                    "数据库", GlobalConstants.currentDevice);
            }

        }

        private DateTime manualSaveTime;
        private void button1_Click(object sender, EventArgs e)
        {
            FileUtil.getInstance().writeDataManual();
            addManualDataIndex();
            writeManualData();
            UIUtil.getInstance().alert("保存成功.");
        }

        private void addManualDataIndex()
        {
            manualSaveTime = DateTime.Now;
            foreach (string key in GlobalConstants.channelTypeMap.Keys)
            {
                checkChannelManualDataIndex(key, GlobalConstants.channelTypeMap[key].ToString());
            }
        }

        private void checkChannelManualDataIndex(string channelCode, string channelType)
        {
            if (channelType.Equals("压力") && !GlobalConstants.configPT)
            {
                return;
            }
            if (channelType.Equals("流量") && !GlobalConstants.configFT)
            {
                return;
            }
            if (channelType.Equals("温度") && !GlobalConstants.configTE)
            {
                return;
            }
            DataTable td = normaldataTableAdapter.GetDataBy3(GlobalConstants.currentDevice,
                channelCode, manualSaveTime, true);
            if (td.Rows.Count == 0)
            {
                normaldataTableAdapter.Insert(channelType, channelCode, manualSaveTime,
                    "数据库", GlobalConstants.currentDevice, true);
            }

        }

        private void writeManualData()
        {
            List<ArrayList> data;
            foreach (string key in GlobalConstants.currentData.Keys)
            {
                data = GlobalConstants.currentData[key];
                string dataString = ushortArray2String(data);
                this.normaldatamanualTableAdapter.InsertQuery(key, manualSaveTime,
                    dataString, 0, GlobalConstants.currentDevice);
            }
        }

        private string ushortArray2String(List<ArrayList> al)
        {
            string[] strArray = new string[al.Count];
            for(int i=0; i<al.Count; i++)
            {
                string dataString = al[i][1].ToString();
                strArray[i] = dataString;
            }
            return string.Join(",", strArray); 
        }

        private void channelftBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.channelftBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.cUPDataDataSet);

        }
    }
}
